package com.darren.euc.service.impl;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.darren.euc.dao.OrderDao;
import com.darren.euc.entity.Contract;
import com.darren.euc.entity.ContractProduct;
import com.darren.euc.entity.Order;
import com.darren.euc.entity.PageBean;
import com.darren.euc.service.OrderService;
import com.darren.euc.util.Constant;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;


@Service
public class OrderServiceImpl implements OrderService {
	
	private static final Logger log = Logger.getLogger(OrderServiceImpl.class);
	
	@Autowired
    private OrderDao orderDao;
	

    @Override
    public Order save(Order order) {
        return orderDao.save(order);
    }
    
    @Override
    public BigInteger getCurrentDayCount(Integer orderId) {
        return orderDao.getCurrentDayCount(orderId);
    }

    @Override
    public Order update(Order order) {
        return orderDao.update(order);
    }
    
    
    @Override
    public void delete(Order order) {
    	orderDao.delete(order);
    }
    
	@Override
	public List<Order> getAll() {
		return orderDao.getAll();
	}
	
	
	@SuppressWarnings("rawtypes")
	public PageBean queryForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){		
		String HQL = null;
		String likes = null;
		String equals = null;
			List<String> parameters = new ArrayList<String>();
		JSONObject likeJson = requestJson.getJSONObject("like");
		Iterator likeIterator = likeJson.keys();
		while(likeIterator.hasNext()){
			String key = (String) likeIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = likeJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				likes = (likes == null?"": likes + " OR ") +  key + " like ? ";
				parameters.add("%"+value+"%");
			}
		}
		HQL = likes == null?null:(" (" + likes + ") ");		
		JSONObject equalsJson = requestJson.getJSONObject("equals");
        Iterator equalsIterator = equalsJson.keys();        
		while(equalsIterator.hasNext()){
			String key = (String) equalsIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = equalsJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
				parameters.add(value);
			}
		}		
		if(HQL != null){
			if(equals != null){
				HQL = HQL + " and " + equals;
			}
		}else{
			HQL = equals;
		}
		HQL = " from Order " + (HQL == null?"":" where " + HQL) + " order by displaySequence asc";
		return orderDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
	}
	
	@SuppressWarnings("rawtypes")
	public PageBean querySeatOrderForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){		
		String HQL = null;
		String likes = null;
		String equals = null;
		List<Object> parameters = new ArrayList<Object>();
		JSONObject likeJson = requestJson.getJSONObject("like");
		Iterator likeIterator = likeJson.keys();
		while(likeIterator.hasNext()){
			String key = (String) likeIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = likeJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				likes = (likes == null?"": likes + " OR ") +  key + " like ? ";
				parameters.add("%"+value+"%");
			}
		}
		HQL = likes == null?null:(" (" + likes + ") ");		
		JSONObject equalsJson = requestJson.getJSONObject("equals");
        Iterator equalsIterator = equalsJson.keys();  
        String startDate = "";
        String endDate = "";
		while(equalsIterator.hasNext()){
			String key = (String) equalsIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = equalsJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				if("searchTimeStart".equals(key)){
					if(value != null){
						startDate = value;
					}
					/*if(value!=null){
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
					try {
						Date startDate = (Date)format.parse(value);
						parameters.add(startDate);
					} catch (ParseException e) {
						log.error(e.getMessage(),e);
					} 
					//equals = (equals == null?"": ""+equals + " and ") +  " salesTime >= ? ";	
					}*/
				}else if("searchTimeEnd".equals(key)){
					if(value != null){
						endDate = value;
					}
					
					/*DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
					try {
						Date endDate = (Date)format.parse(value);
						Calendar calendar = Calendar.getInstance(); 
						calendar.setTime(endDate);
						calendar.add(Calendar.DATE,1); 				
						parameters.add(calendar.getTime());
					} catch (ParseException e) {
						log.error(e.getMessage(),e);
					} 
					equals = (equals == null?"": ""+equals + " and ") +  " salesTime <= ? ";*/
				}else if("spaceId".equals(key)){
					equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
					parameters.add(Integer.parseInt(value));
				}else{
					equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
					parameters.add(value);
				}				
			}
		}	
		
		
		if(startDate!="" && endDate !=""){
			if(startDate.equals(endDate)){
				equals = (equals == null?"": ""+equals + " and ") + "( sales_time = '"+startDate+" 00:00:00')";

			}else{
				equals = (equals == null?"": ""+equals + " and ") + "( sales_time between '"+startDate+" 00:00:00'  and '"+endDate+" 23:59:59')";
			}
		}else{
			if(startDate!=""){
				equals = (equals == null?"": ""+equals + " and ") + " sales_time >= '"+startDate+" 00:00:00'";
			}
			if(endDate!=""){
				equals = (equals == null?"": ""+equals + " and ") + " sales_time <= '"+endDate+" 23:59:59'";
			}
		}
		if(HQL != null){
			if(equals != null){
				HQL = HQL + " and " + equals;
			}
		}else{
			HQL = equals;
		}
		HQL = " from Order " + (HQL == null?"":" where " + HQL) + " order by salesTime desc ";
		PageBean forReturn =  orderDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
		forReturn.setList(getRoomList(forReturn.getList()));
		return forReturn;
	}

	private List getRoomList(List<Order> list) {
		for(Order one:list){
			if(Constant.ORDER_TYPE_SEAT.equals(one.getOrderType()))
				one.setRoomNames(this.getRoomNames(one));
		}
		return list;
	}

	/**
	 * 获取room名字
	 * @param one
	 * @return
	 */
	private String getRoomNames(Order one) {
		StringBuffer sb = new StringBuffer();
		List<Contract> contracts = one.getContractList();
		if(CollectionUtils.isEmpty(contracts))
			return "";
		for(Contract contract:contracts){
			//得到产品
			if(Constant.CONTRACT_TYPE_GETIN.equals(contract.getContractType())){
				List<ContractProduct> cps = contract.getContractProductList();
				if(!CollectionUtils.isEmpty(cps)){
						cps.forEach(cp -> sb.append(cp.getRoomName()).append(","));
				}
			}
		}
		return sb.length()>0?sb.substring(0,sb.length()-1):"";
	}

}